package br.com.javamagazine;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class ImageDownloadServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("image/jpg");

		String path = req.getQueryString();

		HttpURLConnection conexao = null;

		try {
			URL url = new URL(path);
			conexao = (HttpURLConnection) url.openConnection();
			conexao.setRequestProperty("Request-Method", "GET");

			conexao.setDoInput(true);
			conexao.setDoOutput(false);

			conexao.connect();

			InputStream stream = conexao.getInputStream();

			byte[] buffer = new byte[8192];
			int len = 0;
			
			OutputStream byteOut = resp.getOutputStream();
			
			while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
				byteOut.write(buffer, 0, len);
			}
			stream.close();
					
			byteOut.flush();
			byteOut.close();
			
		} catch (Exception e) {

		}

	}
}
